<template>
  <div>
    <!--  资源领域编辑添加组件-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="categoryData">
        <el-form-item label="资源领域名称" :label-width="formLabelWidth">
          <el-input v-model="categoryData.sourceName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="categoryData.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
import {resourceCreate, gainByIdResource, resourceUpdate} from '@/api/resource/resource'

export default {
  name: "CreateUpdateResource",
  data() {
    return {
      //创建 true
      isCreate: true,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      categoryData: {
        id: undefined,
        sourceName: '',
        sort: 0
      },
    }
  },
  methods: {
    showAndInit(categoryId = 0) {
      // this.categoryData= {
      //   id: undefined,
      //       sourceName: '',
      //       sort: 0
      //   }
      //id有数据就是false 编辑,没id是true是新增
      this.isCreate = categoryId < 1;
      console.log("this.isCreate", this.isCreate);
      this.dialogFormVisible = true
      if (this.isCreate) {
        console.log("新建")
      } else {
        console.log("编辑")
        //领域资源详情
        gainByIdResource(categoryId).then(res => {
          console.log("编辑res",res);
          //可以先查询list使用find过滤出来要的数据
          this.categoryData = res.data.data;
          // console.log("res",res);
        })
      }

    },
    onSubmit() {
      //编辑 false ，新建   true
      if (this.isCreate) {
        //资源领域新增
        resourceCreate(this.categoryData).then(res => {
          console.log(res);
          if (res.data.code == '200') {
            this.$message.success(`${this.title}资源领域类别成功!`)
            //向父组件发送消息(自定义事件)
            this.$emit('changeCategory')
          } else {
            this.$message.error(`${this.title}资源领域类别失败!`)
          }
          this.dialogFormVisible = false;
        })
      } else {
        console.log("后端接收的id",this.categoryData);
        //资源领域编辑
        resourceUpdate(this.categoryData).then(res => {
          console.log(res);
          if (res.data.code == '200') {
            this.$message.success(`${this.title}资源领域类别成功!`)
            //向父组件发送消息(自定义事件)
            this.$emit('changeCategory')
          } else {
            this.$message.error(`${this.title}资源领域类别失败!`)
          }
          this.dialogFormVisible = false;
        })
      }

    }
  },
  computed: {
    title() {
      return this.isCreate ? '新建' : '编辑'
    }
  }
}
</script>


<style scoped>

</style>
